package com.yaozheng.vocationaltraining.fragment.exam;

import android.content.Intent;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.HomeActivity;
import com.yaozheng.vocationaltraining.adapter.PKMorePersonPlayerStatusAdapter;
import com.yaozheng.vocationaltraining.adapter.PKPlayerStatusAdapter;
import com.yaozheng.vocationaltraining.bean.PKMorePersonPlayerStatusBean;
import com.yaozheng.vocationaltraining.bean.PKPlayerStatusBean;
import com.yaozheng.vocationaltraining.fragment.BaseFragment;
import com.yaozheng.vocationaltraining.iview.exam.IPKMorePersonConfirmView;
import com.yaozheng.vocationaltraining.service.exam.PKMorePersonConfirmService;
import com.yaozheng.vocationaltraining.service.impl.exam.PKConfirmServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.exam.PKMorePersonConfirmServiceImpl;
import com.yaozheng.vocationaltraining.utils.ACache;
import com.yaozheng.vocationaltraining.utils.BitmapLoader;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;

/**
 * Created by moon on 2017/11/16.
 */

@EFragment(R.layout.activity_pk_more_person_confirm)
public class PKMorePersonConfirmFragment extends BaseFragment
        implements IPKMorePersonConfirmView {

    @ViewById
    ListView listView;
    PKMorePersonPlayerStatusAdapter pkMorePersonPlayerStatusAdapter;
    ArrayList<PKMorePersonPlayerStatusBean> pkMorePersonPlayerStatusData = new ArrayList<>();

    @ViewById
    TextView headTitleText;

    @ViewById
    Button start_button;
    @ViewById
    Button leave_button;

    @ViewById
    TextView remaining_time_textview;

    @ViewById
    LinearLayout not_ready_layout;
    @ViewById
    TextView ready_layout;
    @ViewById
    LinearLayout not_ready_button_layout;

    @Bean(PKMorePersonConfirmServiceImpl.class)
    PKMorePersonConfirmService pkMorePersonConfirmService;

    private BitmapLoader userBitmapLoader;
    public HomeActivity getHomeActivity() {
        return (HomeActivity) getActivity();
    }


    public int getRoomId() {
        return roomId;
    }

    public void setRoomId(int roomId) {
        this.roomId = roomId;
    }

    int roomId;

    public int getRemainingTime() {
        return remainingTime;
    }

    public void setRemainingTime(int remainingTime) {
        this.remainingTime = remainingTime;
    }

    int remainingTime;

    public int getGameId() {
        return gameId;
    }

    public void setGameId(int gameId) {
        this.gameId = gameId;
    }

    int gameId;

    CountDownTimer cdt;
    static int count = 0;

    boolean alreadyPK = false;

    @AfterViews
    public void initView() {
        headTitleText.setText("比赛确认");
        pkMorePersonConfirmService.init(this);
        userBitmapLoader = new BitmapLoader(Glide.with(this), R.drawable.user_img);

        count = 0;


        pkMorePersonPlayerStatusAdapter = new PKMorePersonPlayerStatusAdapter(this.getActivity()
                ,pkMorePersonPlayerStatusData);
        listView.setAdapter(pkMorePersonPlayerStatusAdapter);

        not_ready_layout.setVisibility(View.VISIBLE);
        not_ready_button_layout.setVisibility(View.VISIBLE);
        ready_layout.setVisibility(View.GONE);

        if (remainingTime < 1){//如果我的状态为已准备好
            not_ready_layout.setVisibility(View.GONE);
            not_ready_button_layout.setVisibility(View.GONE);
            ready_layout.setVisibility(View.VISIBLE);

            //remainingTime = 60;
        }

//        if(remainingTime > 0){
//            cdt = new CountDownTimer(remainingTime * 1000 + 2 * 1000, 1000 ) {
//                @Override
//                public void onTick(long millisUntilFinished) {
//                    if(remainingTime < 1){
//                        remaining_time_textview.setText("0");
//                    }else {
//                        remainingTime = remainingTime - 1;
//                        remaining_time_textview.setText(remainingTime  +"" );
//                    }
//
//                    count ++;
//                    if (count % 3 == 0){
//                        onRefresh();
//                    }
//                }
//                @Override
//                public void onFinish() {
//                    count = 0;
//                    onRefresh(true);
//                }
//            };
//            cdt.start();
//        }

        startTiming();

        onRefresh();
    }

    /**
     * 开始计时
     */
    @Background
    public void startTiming() {
        if (alreadyPK && isResponseResult()) {
            try {
                onRefresh();
                Thread.sleep(500);
                updateTimingUI();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @UiThread
    public void updateTimingUI() {
        startTiming();
    }

    private void onRefresh(boolean flag) {
        pkMorePersonConfirmService.list(roomId,flag);
    }
    private void onRefresh() {
        onRefresh(false);
    }



    @Click(R.id.start_button)
    public void startButtonClick() {//
        pkMorePersonConfirmService.start(gameId);
    }

    @Click(R.id.leave_button)
    public void leaveButtonClick() {//
        pkMorePersonConfirmService.leave(gameId);
    }



    @UiThread
    @Override
    public void responseListSuccess(JSONObject jsonObject,boolean flag) {
        try {
            cancelLoadDataProgressDialog();
            JSONObject roomObject = TypeUtils.getJsonObject(jsonObject, "data","room");
            remainingTime = roomObject.getInt("remaining");
            remaining_time_textview.setText(remainingTime  +"" );

//            if(remainingTime < 1){
//
//                if(remainingTime > 0){
//                    cdt = new CountDownTimer(remainingTime * 1000 + 2 * 1000, 1000 ) {
//                        @Override
//                        public void onTick(long millisUntilFinished) {
//                            if(remainingTime < 1){
//                                remaining_time_textview.setText("0");
//                            }else {
//                                remainingTime = remainingTime - 1;
//                                remaining_time_textview.setText(remainingTime  +"" );
//                            }
//
//                            count ++;
//                            if (count % 3 == 0){
//                                onRefresh();
//                            }
//                        }
//                        @Override
//                        public void onFinish() {
//                            count = 0;
//                            onRefresh(true);
//                        }
//                    };
//                    cdt.start();
//                }
//            }


            JSONArray dataList = TypeUtils.getJsonArray(jsonObject, "data","players");
            if (dataList != null) {
                pkMorePersonPlayerStatusData.clear();

                for (int i = 0; i < dataList.size(); i++) {
                    JSONObject playerJsonObject = dataList.getJSONObject(i);
                    gameId = playerJsonObject.getInt("gameId");
                    PKMorePersonPlayerStatusBean bean = new PKMorePersonPlayerStatusBean();
                    bean.setId(playerJsonObject.getInt("id"));
                    bean.setGameId(playerJsonObject.getInt("gameId"));
                    bean.setPlayerId(playerJsonObject.getInt("playerId"));
                    bean.setStatus(playerJsonObject.getInt("status"));
                    bean.setStartTime(playerJsonObject.getString("startTime"));
                    bean.setEndTime(playerJsonObject.getString("endTime"));
                    bean.setDurationTime(playerJsonObject.getString("durationTime"));

                    Integer score = TypeUtils.getJsonInteger(playerJsonObject,"score");
                    bean.setScore(score== null ?0:score);
                    Integer result = TypeUtils.getJsonInteger(playerJsonObject,"result");
                    bean.setResult(result== null ?0:result);
                    bean.setPlayerName(playerJsonObject.getString("playerName"));
                    bean.setPlayerAvatar(playerJsonObject.getString("playerAvatar"));


                    pkMorePersonPlayerStatusData.add(bean);
                }

                if(flag){
                    if(canStartLoadQuestion()){//调 用考试接口，拉取试卷
                        alreadyPK = true;
                        if (cdt != null){
                            cdt.cancel();
                        }
                        showOperatingProgressDialog("获取试卷中...");
                        pkMorePersonConfirmService.loadQuestionList(
                                gameId);
                    }else {
                        //Thread.sleep(500);
                        //onRefresh(true);
                    }
                }else {
                    pkMorePersonPlayerStatusAdapter.setData(pkMorePersonPlayerStatusData);
                    pkMorePersonPlayerStatusAdapter.notifyDataSetChanged();
                }

            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
    }

    @UiThread
    @Override
    public void leaveError(String error) {
        //Toast.makeText(getActivity(),error,Toast.LENGTH_SHORT).show();
    }

    @UiThread
    @Override
    public void leaveSuccess(JSONObject jsonObject) {
        getHomeActivity().backClick();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (cdt != null){
            cdt.cancel();
        }
    }

    private boolean canStartLoadQuestion() {
        LogUtils.println("remainingTime="+remainingTime);
        int count = 0;
        for (PKMorePersonPlayerStatusBean bean : pkMorePersonPlayerStatusData){
            LogUtils.println("status="+bean.getStatus());
            if (bean.getStatus() == 1){//有玩家处于比赛中，则立即调用考试接口，进行考试
                return true;
            }else if (bean.getStatus() == 0)
            {
                count ++;
            }
        }

        if (remainingTime > 0){
            return false;
        }

        if (count > 1){
            return true;
        }
        return false;
    }

    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {

    }

    @UiThread
    @Override
    public void responseError(String error) {
        //Toast.makeText(this.getHomeActivity(),error,Toast.LENGTH_SHORT).show();
        if(getHomeActivity() != null){
            getHomeActivity().backClick();
        }

    }

    @UiThread
    @Override
    public void startPkMorePersonSuccess(JSONObject jsonObject) {
        not_ready_layout.setVisibility(View.GONE);
        not_ready_button_layout.setVisibility(View.GONE);
        ready_layout.setVisibility(View.VISIBLE);

        //onRefresh();
    }

    @UiThread
    @Override
    public void startPkMorePersonError(String error) {
        Toast.makeText(this.getActivity(),error,Toast.LENGTH_SHORT).show();
    }

    @UiThread
    @Override
    public void getQuestionListSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        JSONObject paperJsonObject = TypeUtils.getJsonObject(jsonObject,
                "data", "game","paper");
        if(!paperJsonObject.containsKey("duration")){
            paperJsonObject.put("duration",TypeUtils.getJsonObject(jsonObject,
                    "data", "game").getInt("duration"));
        }
        // 进入考试
        Intent intent = getBaseActivity().getIntent();
        intent.putExtra("examType", "8");//8表示PK赛
        intent.putExtra("paperId",
                TypeUtils.getJsonInteger(paperJsonObject, "id"));
        intent.putExtra("startTimeLong", System.currentTimeMillis());
        intent.putExtra("paperJsonObjectStr", paperJsonObject.toString());
        intent.putExtra("examTitle", "PK赛");
        intent.putExtra("gameId", gameId);
        getHomeActivity().openOnlineExamFragment();
    }

    @UiThread
    @Override
    public void getQuestionListError(String error) {
        Toast.makeText(this.getActivity(),error,Toast.LENGTH_SHORT).show();
    }
}
